/** 定时备份 */
let qiniu = require('qiniu');
let path = require('path');
let fse = require('fs-extra');// fs 模块扩展
let archiver = require('archiver');// 文件压缩
let { db } = require('../service');// 数据库
// config
const CONFIG = {
  accessKey: 'CEVcN2KwNIOEV3QjUiabL-3mkfhntcvBs4AWs1w_',
  secretKey: '7ILy0lu4FJVJ4LX-0U8_1a4PSAWoxZcfR4B0M6DF',
  bucket: 'brower-info-list',
  expires: 60 * 60 * 60,
  path: path.resolve('.', 'auto-backs-dir')
};
// 配置
let config = new qiniu.conf.Config();
// 空间对应的机房
config.zone = qiniu.zone.Zone_z2;
let formUploader = new qiniu.resume_up.ResumeUploader(config);
let putExtra = new qiniu.resume_up.PutExtra();

/**
 * 备份
 */
function backup() {
  let nowTime = Date.now();
  // 最近备份时间
  db.set('lastBackupTime', nowTime).write();
  zipFileDir(`wxBackups-${nowTime}.zip`);
}

/**
 * 文件压缩
 */
function zipFileDir(file_name) {
  let zipPath = path.join(CONFIG.path, file_name);
  fse.ensureFileSync(zipPath);

  let output = fse.createWriteStream(zipPath);
  let archive = archiver('zip', {
    zlib: {
      level: 9
    }
  });
  // 流文件
  output.on('close', function() {
    // console.log(archive.pointer()/1024/1024 + 'M');
    console.log(`压缩完成：${file_name}`);
    putFileToQinui(file_name);
  });
  // 需要压缩的dir
  let zipDirList = [
    {
      source: 'publish',
      type: 'dir'
    },
    {
      source: 'resource',
      type: 'dir'
    },
    {
      source: 'DB/db.json',
      type: 'file'
    }
  ];
  // 压缩
  archive.pipe(output);
  zipDirList.forEach((item) => {
    if(item.type === 'dir') {
      archive.directory(path.resolve('.', item.source), item.source);
    } else {
      archive.file(item.source, {
        name: item.source
      });
    }
  });
  archive.finalize();
}

/**
 * 上传文件
 */
function putFileToQinui(key) {
  // 生成 KEY TOKEN
  let putPolicy = new qiniu.rs.PutPolicy({
    scope: CONFIG.bucket,
    expires: CONFIG.expires
  });
  let mac = new qiniu.auth.digest.Mac(CONFIG.accessKey, CONFIG.secretKey);
  let uploadToken = putPolicy.uploadToken(mac);
  let localFile = path.join(CONFIG.path, key);
  // 扩展参数
  // putExtra.params = {
  //   "x:name": "",
  //   "x:age": 27,
  // }
  putExtra.fname = key;
  // 如果指定了断点记录文件，那么下次会从指定的该文件尝试读取上次上传的进度，以实现断点续传
  putExtra.resumeRecordFile = 'progress.log';
  // put
  formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr, respBody, respInfo) {
    if (respErr) {
      console.log(respErr);
      throw respErr;
    }
    if (respInfo.statusCode == 200) {
      console.log(respBody);
    } else {
      console.log(respInfo.statusCode);
      console.log(respBody);
    }
  });
}

// 定时器
let schedule = require('node-schedule');
// 参数解释
// * * * * * *
// ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │ │
// │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
// │ │ │ │ └───── month (1 - 12)
// │ │ │ └────────── day of month (1 - 31)
// │ │ └─────────────── hour (0 - 23)
// │ └──────────────────── minute (0 - 59)
// └───────────────────────── second (0 - 59, OPTIONAL)
let bakck_task = () => {
  // 每周 1 的 24 点 0 分 30 秒触发：30 0 0 * * 1
  schedule.scheduleJob('0 0 0 1 * *',()=>{
    console.log('自动执行备份：' + new Date());
    backup();
  });
}
// 启动 定时器
bakck_task();